/* Copyright 2001,2002,2003 NAH6 BV
 * All Rights Reserved
 *
 *  $Header: /var/lib/cvs/secphone/ui/userdata/UDCAutoAnswer.cpp,v 1.6 2003/11/21 16:12:58 itsme Exp $
 *
 *
 *  this handles the autoanswer userdata messages
 *
 *  this class should be better named 'CallControl'
 *
 */

#include "CPhone.h" // theApp  .. needs to be included before the others, to avoid 'new' error in stl_evc
#include "debug.h"

#include "UDCAutoAnswer.h"

#include "CPhoneDlg.h"
#include "UserdataHandler.h"
#include "PhoneHandler.h"
#include "PhoneOptions.h"

#include <algorithm>

// todo: rename this class to 'CallControl'
// todo: add more connection negotiation type properties here.
//      like - 'I need you to hangup'  ( for modem )

UDCAutoAnswer::UDCAutoAnswer(CCPhoneDlg& dlg) : m_dlg(dlg)
{
    theApp.m_ud->RegisterUserdataHandler(UDCLT_AUTOANSWER, this);
}

UDCAutoAnswer::~UDCAutoAnswer()
{
    theApp.m_ud->UnRegisterUserdataHandler(UDCLT_AUTOANSWER);
}

bool UDCAutoAnswer::HandleUserdataMessage(const ByteVector& data)
{
    if (data.size()!=1)
    {
        debug("ERROR: invalid aa msg\n");
        return false;
    }

    bool res= false;
    switch(data[0])
    {
    case AAMSG_ANSWERED: 
        {
            res= theApp.m_aa->HandleAnsweredMessage();
        }
        break;
    case AAMSG_WAITING: 
        {
            res= theApp.m_aa->HandleWaitingMessage();
        }
    case AAMSG_HANGUP:
        {
            res= theApp.m_aa->HandleHangupMessage();
        }
        break;
    }

    return res;
}

bool UDCAutoAnswer::HandleWaitingMessage()
{
    theApp.m_phone->SignalRcvAutoAnswerWait();
    return true;
}


bool UDCAutoAnswer::HandleAnsweredMessage()
{
    theApp.m_phone->SignalRcvAutoAnswerConnect();

    return true;
}

// this message is there to work around a bug in tapi where
// only one side can hangup the connection.
bool UDCAutoAnswer::HandleHangupMessage()
{
    theApp.m_phone->SignalPhoneRemoteHangup();
    return true;
}
bool UDCAutoAnswer::SendAnsweredMessage()
{
    ByteVector msg;
    bufpack(msg, "C", AAMSG_ANSWERED);
    bool res= theApp.m_ud->SendStateMessage(UDCLT_AUTOANSWER, msg, g_options.aa_state_resend_delay);

    return res;
}
bool UDCAutoAnswer::SendWaitingMessage()
{
    ByteVector msg;
    bufpack(msg, "C", AAMSG_WAITING);
    bool res= theApp.m_ud->SendStateMessage(UDCLT_AUTOANSWER, msg, g_options.aa_state_resend_delay);

    return res;
}
bool UDCAutoAnswer::SendHangupMessage()
{
    ByteVector msg;
    bufpack(msg, "C", AAMSG_HANGUP);
    bool res= theApp.m_ud->SendSingleMessage(msg);

    return res;
}
bool UDCAutoAnswer::StopSending()
{
    return theApp.m_ud->StopStateMessage(UDCLT_AUTOANSWER);
}
